package org.kiwi.job.call.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.kiwi.http.support.HttpCallback;
import org.kiwi.http.support.HttpTemplate;
import org.kiwi.http.support.enums.RequestMethod;
import org.kiwi.job.vo.BaseRequest;
import org.kiwi.job.vo.BaseResponse;
import org.kiwi.util.IPUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import static org.kiwi.job.constant.CommonConstant.FAIL;

/**
 * @email jack.liu.19910921@gmail.com
 * Created by jack on 17/2/21.
 */
public abstract class AbstractRemoteCallByHttpService {

    protected final Logger LOGGER = LoggerFactory.getLogger(getClass());

    @Autowired
    protected HttpTemplate httpTemplate;

    public BaseResponse call(String httpPath) {
        BaseResponse baseResponse;
        try {
            BaseRequest baseRequest = buildRequest();

            LOGGER.info("触发{}域[{}]请求参数:[{}]", getDomainDescription(), httpPath, JSON.toJSONString(baseRequest));

            String result = httpTemplate.execute(getDomain() + httpPath, baseRequest, getRequestMethod(), new HttpCallback<String>() {

                @Override
                public String doParseResult(String result) {
                    return result;
                }
            });

            baseResponse = JSONObject.parseObject(result, BaseResponse.class);

            LOGGER.info("触发{}域[{}]响应结果:[{}]", getDomainDescription(), httpPath, JSON.toJSONString(baseResponse));

        } catch (Exception e) {
            LOGGER.error("调用" + getDomainDescription() + "API接口" + httpPath + "异常", e);
            baseResponse = new BaseResponse(FAIL, "调用" + getDomainDescription() + "API接口" + httpPath + "异常:" + e.getMessage(), "500");
        }
        return baseResponse;
    }

    private BaseRequest buildRequest() {
        BaseRequest baseRequest = new BaseRequest();
        baseRequest.setReqTime(System.currentTimeMillis() + "");
        baseRequest.setIpAddress(IPUtil.getLocalIP());

        populateRequest(baseRequest);

        return baseRequest;
    }

    protected abstract void populateRequest(BaseRequest baseRequest);

    protected abstract String getDomain();

    protected abstract String getDomainDescription();

    protected abstract RequestMethod getRequestMethod();

}
